---
import { getPageNameFromPath } from '@components/docs/utils/urlPaths';
import ExampleRunnerContainer from '@components/example-runner/components/ExampleRunnerContainer.astro';
import { getIsDev } from '@utils/env';
import { DocsExampleRunner } from './DocsExampleRunner';
import { DISABLE_EXAMPLE_RUNNER } from '@constants';
import { getGeneratedContents, type GeneratedExampleParams } from '@components/example-generator';
import { getSupportedFrameworks } from '@components/docs/utils/filesData';

interface Props {
    title: string;
    name: string;
    exampleHeight?: number;
    suppressDarkMode?: boolean;
    typescriptOnly?: boolean;
    consoleBufferSize?: number;
}

const { title, name, exampleHeight, typescriptOnly, suppressDarkMode, consoleBufferSize } = Astro.props as Props;

const pageName = getPageNameFromPath(Astro.url.pathname);
const isDev = getIsDev();

const supportedFrameworks = await getSupportedFrameworks({ pageName, exampleName: name });
const generatedExampleParams: GeneratedExampleParams = {
    type: 'docs',
    // If there are supported frameworks, take the first one, otherwise the contents should be the same as vanilla
    framework: supportedFrameworks?.values().next().value || 'vanilla',
    pageName,
    exampleName: name,
};

let hasExampleConsoleLog = false;
try {
    // NOTE: Even though we have the contents at build time, we are not passing
    // it into the component, so that we can load the contents at runtime.
    // This avoids the page being bigger than it needs to be, if the user does
    // not scroll to the example.
    const contents = await getGeneratedContents(generatedExampleParams);
    // Get whether example has console log component at build time, so that we
    // can show it on page load.
    hasExampleConsoleLog = Boolean(contents?.hasExampleConsoleLog);
} catch (error) {
    console.error('Error generating contents for:', generatedExampleParams);
}
---

{
    !DISABLE_EXAMPLE_RUNNER && (
        <ExampleRunnerContainer
            exampleHeight={exampleHeight}
            pageName={pageName}
            exampleName={name}
            hasExampleConsoleLog={hasExampleConsoleLog}
        >
            <DocsExampleRunner
                client:only="react"
                title={title}
                name={name}
                exampleHeight={exampleHeight}
                typescriptOnly={typescriptOnly}
                suppressDarkMode={suppressDarkMode}
                pageName={pageName}
                isDev={isDev}
                hasExampleConsoleLog={hasExampleConsoleLog}
                consoleBufferSize={consoleBufferSize}
            />
        </ExampleRunnerContainer>
    )
}
